package com.jzy.weblog.jwt.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jzy.weblog.common.utils.Response;
import org.springframework.http.HttpStatus;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class ResultUtil {

    /**
     * 成功响参
     * @param response
     * @param result
     * @throws IOException
     */
    public static void ok(HttpServletResponse response, Response<?> result) throws IOException {
        response.setCharacterEncoding("utf-8"); //设置响应的 字符编码为 UTF-8
        response.setStatus(HttpStatus.OK.value()); //设置状态码为 200，表示请求成功
        response.setContentType("application/json;charset=utf-8"); //告诉浏览器：响应内容是 JSON，编码是 UTF-8
        PrintWriter writer = response.getWriter();

        ObjectMapper mapper = new ObjectMapper(); //使用 Jackson 的 ObjectMapper 把 result 对象转为 JSON 字符串
        writer.write(mapper.writeValueAsString(result)); // 写入响应体中
        writer.flush(); //刷新确保发送
        writer.close();
    }

    /**
     * 失败响参
     * @param response
     * @param result
     * @throws IOException
     */
    public static void fail(HttpServletResponse response, Response<?> result) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setStatus(HttpStatus.OK.value()); //HTTP 状态码始终返回 200，表示请求成功收到了，但具体业务是否成功，由响应体中的 "code" 字段决定
        response.setContentType("application/json");
        PrintWriter writer = response.getWriter();

        ObjectMapper mapper = new ObjectMapper();
        writer.write(mapper.writeValueAsString(result));
        writer.flush();
        writer.close();
    }

    /**
     * 失败响参
     * @param response
     * @param status 可指定响应码，如 401 等
     * @param result
     * @throws IOException
     */
    public static void fail(HttpServletResponse response, int status, Response<?> result) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setStatus(status);
        response.setContentType("application/json");
        PrintWriter writer = response.getWriter();

        ObjectMapper mapper = new ObjectMapper();
        writer.write(mapper.writeValueAsString(result));
        writer.flush();
        writer.close();
    }

}
